//
//  SearchViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/1.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "SearchViewController.h"
#import "HouseDetailViewController.h"
#import "UserHomepageViewController.h"

#import "HouseListTableViewCell.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/UIButton+WebCache.h>
#import <MobClick.h>

#import "ACMacros.h"
#import "Utility.h"
#import "Constants.h"

#import "HttpServer.h"
#import "House.h"

@interface SearchViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UITextFieldDelegate, HouseListTableViewCellDelegate>


@end

@implementation SearchViewController
{
    __weak IBOutlet UIButton *cancelButton;
    __weak IBOutlet UITextField *searchTextField;
    __weak IBOutlet UIView *searchTitleView;
    
    BOOL isSearching;
    CGFloat oldOffset;
    
    NSMutableArray *housesArray;
    NSMutableArray *searchHistory;
    NSMutableArray *teams;
    NSMutableArray *pois;
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = true;
    searchTitleView.layer.borderColor = [RGBACOLOR(71, 62, 58, 0.7) CGColor];
    if (self.searchText == nil || [self.searchText isEqual:@""]) {
        [searchTextField setText:nil];
        isSearching = false;
        [searchTextField becomeFirstResponder];
    } else {
        [searchTextField setText:self.searchText];
        [self searchWithKeyword:searchTextField.text];
    }
    [self.tableView reloadData];
    [MobClick beginLogPageView:@"搜索页"];
}

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = false;
    [searchTextField resignFirstResponder];
    [Utility setObject:searchHistory key:@"searchHistory"];
    self.searchText = nil;
    [MobClick endLogPageView:@"搜索页"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureSearchHistory];
    [self configureSearchTextField];
    [self configureTableView];
    if (self.searchText == nil || [self.searchText isEqual:@""]) {
    } else {
        [searchTextField setText:self.searchText];
    }
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavior
- (void)configureSearchHistory {
    searchHistory = [Utility getObjectForKey:@"searchHistory"];
    if (searchHistory == nil || searchHistory.count == 0) {
        searchHistory = [[NSMutableArray alloc]init];
    }
}

- (void)configureSearchTextField {
    searchTextField.delegate = self;
}

- (void)configureTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, Main_Screen_Width, Main_Screen_Height - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:[UIColor whiteColor]];
    [self.tableView registerNib:[UINib nibWithNibName:@"HouseListTableViewCell" bundle:nil] forCellReuseIdentifier:@"HouseListTableViewCell"];
    oldOffset = 0;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (isSearching) {
        return housesArray.count;
    } else {
        if (pois.count == 0) {
            return searchHistory.count;
        } else {
            return pois.count;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (isSearching) {
        NSInteger row = indexPath.row;
        House *house = [[House alloc]initWithDic:[housesArray[row] objectForKey:@"house"]];
        teams = [housesArray[row] objectForKey:@"teams"];
        HouseListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HouseListTableViewCell"];
        [cell setDelegate:self];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.houseImageView sd_setImageWithURL:[NSURL URLWithString:house.cover] placeholderImage:[UIImage new]];
        [cell.houseNameLabel setText:house.community];
        [cell.houseRemarkLabel setText:[NSString stringWithFormat:@"%@ %d室%d厅%d卫 - %dm² | 入住时间: %@",house.region, house.roomNum, house.hallNum, house.toiletNum, house.area, house.checkinTime]];
        if (house.check) {
            [cell.houseCheckLabel setHidden:false];
            [cell.sourceLeading setConstant:30];
        } else {
            [cell.houseCheckLabel setHidden:true];
            [cell.sourceLeading setConstant:0];
        }
        [cell.houseSourceLabel setText:house.from];
        NSArray *buttonArray = @[cell.headerButton_1, cell.headerButton_2, cell.headerButton_3, cell.headerButton_4, cell.headerButton_5];
        for (UIButton *button in buttonArray) {
            button.hidden = true;
        }
        for (int i = 0; i < teams.count; i++) {
            if (i < buttonArray.count) {
                UIButton *button = buttonArray[i];
                button.hidden = false;
                Leader *leader = [[Leader alloc]initWithDic:teams[i]];
                [button sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?q=60",leader.leaderAvatar]] forState:UIControlStateNormal];
            }
        }
        if (teams.count == 0) {
            [cell.noteLabel setTextAlignment:NSTextAlignmentLeft];
            [cell.noteLabel setText:@"暂无室友小组,快来招募你的室友吧!"];
        } else {
            [cell.noteLabel setTextAlignment:NSTextAlignmentRight];
            [cell.noteLabel setText:[NSString stringWithFormat:@"%d个室长在招募",teams.count]];
        }
        
        return cell;
    } else {
        UITableViewCell *defaultCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"defaultCell"];
        [defaultCell.imageView setImage:[UIImage new]];
        [defaultCell.textLabel setFont:[UIFont systemFontOfSize:15]];
        if (pois.count == 0) {
            [defaultCell.textLabel setText:searchHistory[indexPath.row]];
        } else {
            [defaultCell.textLabel setText:[pois[indexPath.row] objectForKey:@"name"]];
        }
        return defaultCell;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (isSearching) {
        NSInteger row = indexPath.row;
        House *house = [[House alloc]initWithDic:[housesArray[row] objectForKey:@"house"]];
        NSNumber *code = [[NSNumber alloc]initWithInteger:[[house.limits[0] objectForKey:@"code"] integerValue]];
        switch ([code integerValue]) {
            case 1:
                return Main_Screen_Width * 0.6 + 123;
                break;
            default:
                return Main_Screen_Width * 0.6 + 174;
                break;
        }
    } else {
        return 45;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (isSearching) {
        return 0.1;
    } else {
        return 30;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (!isSearching) {
        UITableViewHeaderFooterView *sectionHeaderView = [[UITableViewHeaderFooterView alloc]init];
        UILabel *sectionTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 0, 100, 30)];
        [sectionTitleLabel setFont:[UIFont systemFontOfSize:12]];
        [sectionTitleLabel setText:@"搜索历史"];
        [sectionTitleLabel setTextColor:RGBACOLOR(160, 160, 160, 1)];
        UIButton *cleanHistoryButton = [[UIButton alloc]initWithFrame:CGRectMake(Main_Screen_Width - 56, 0, 56, 30)];
        [cleanHistoryButton setTitle:@"清空" forState:UIControlStateNormal];
        [cleanHistoryButton addTarget:self action:@selector(cleanHistory) forControlEvents:UIControlEventTouchUpInside];
        [cleanHistoryButton.titleLabel setTextAlignment:NSTextAlignmentRight];
        [cleanHistoryButton setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
        [cleanHistoryButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [cleanHistoryButton setTitleColor:RGBACOLOR(160, 160, 160, 1) forState:UIControlStateNormal];
        [cleanHistoryButton setTitleColor:RGBACOLOR(255, 118, 108, 1) forState:UIControlStateHighlighted];
        [cleanHistoryButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [sectionHeaderView addSubview:sectionTitleLabel];
        [sectionHeaderView addSubview:cleanHistoryButton];
        
        return sectionHeaderView;
    } else {
        UITableViewHeaderFooterView *emptyHeaderView = [[UITableViewHeaderFooterView alloc]init];
        return emptyHeaderView;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (isSearching) {
        NSInteger row = indexPath.row;
        HouseDetailViewController *detailVC = [[HouseDetailViewController alloc]init];
        if (housesArray[row] == nil) {
        } else {
            House *house = [[House alloc]initWithDic:[housesArray[row] objectForKey:@"house"]];
            detailVC.houseId = house.houseId;
            [self.navigationController pushViewController:detailVC animated:true];
        }
    } else {
        [searchTextField resignFirstResponder];
        if (pois.count == 0) {
            [searchTextField setText:searchHistory[indexPath.row]];
        } else {
            [searchTextField setText:[pois[indexPath.row] objectForKey:@"name"]];
        }
        [self searchWithKeyword:searchTextField.text];
    }
}

#pragma mark - Triggering Methods
- (IBAction)clickToCancel:(UIButton *)sender {
    [searchTextField resignFirstResponder];
    [self.navigationController popViewControllerAnimated:true];
}

- (void)cleanHistory {
    [searchHistory removeAllObjects];
    [Utility setObject:searchHistory key:@"searchHistory"];
    [self.tableView reloadData];
}

#pragma mark - Scroll view delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < oldOffset) {
        [searchTextField resignFirstResponder];
    }
    oldOffset = scrollView.contentOffset.y;
}

#pragma mark - Text field delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *value = textField.text;
    if ([string isEqual:@""]) {
        value = [value substringToIndex:textField.text.length - 1];
    } else {
        value = [NSString stringWithFormat:@"%@%@",value, string];
    }
    [self matchAutoCompleteArrayWithKeyword:value];
    return true;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return true;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    isSearching = false;
    [pois removeAllObjects];
    [self.tableView reloadData];
    return true;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.text == nil || [textField.text isEqual:@""]) {
        isSearching = false;
        [self.tableView reloadData];
    } else {
        [self searchWithKeyword:textField.text];
    }
}

#pragma mark - Network methods
- (void)searchWithKeyword:(NSString *)keyword {
    searchTextField.text = keyword;
    BOOL dup = false;
    for (NSString *string in searchHistory) {
        if ([string isEqualToString:keyword]) {
            dup = true;
        }
    }
    if (!dup) {
        [searchHistory addObject:keyword];
    }
    NSString *cityCode = [Utility getObjectForKey:kCityCode];
    if (cityCode == nil || [cityCode isEqual:@""]) {
        cityCode = @"3502";
    }
    NSDictionary *params = @{@"cityCode":cityCode, @"keyword":keyword};
    [HttpServer getHousesWithParams:params WithSuccessBlock:^(NSDictionary *housesData) {
        housesArray = [housesData objectForKey:@"houses"];
        isSearching = true;
        [self.tableView reloadData];
    } withFailBlock:^(id failData) {
        NSLog(@"%@", failData);
    }];
}

#pragma mark - Table view cell delegate
- (void)headerButtonClickedWithTag:(NSInteger)tag WithIndex:(NSInteger)index{
    NSArray *tempTeams = [housesArray[index] objectForKey:@"teams"];
    NSDictionary *leaderDic = tempTeams[tag];
    Leader *leader = [[Leader alloc]initWithDic:leaderDic];
    UserHomepageViewController *userHomepageVC = [[UserHomepageViewController alloc]init];
    userHomepageVC.userId = leader.leaderId;
    userHomepageVC.userName = leader.leaderName;
    [self.navigationController pushViewController:userHomepageVC animated:true];
}

#pragma mark - Network methods
- (void)matchAutoCompleteArrayWithKeyword:(NSString *)keyword {
    if (!pois) {
        pois = [[NSMutableArray alloc]init];
    } else {
        [pois removeAllObjects];
    }
    [HttpServer getPoisWithKeyword:keyword WithSuccessBlock:^(NSDictionary *successData) {
        [pois addObjectsFromArray:[successData objectForKey:@"pois"]];
        [self.tableView reloadData];
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
        [pois removeAllObjects];
        [self.tableView reloadData];
    }];
}

@end
